package cn.sciento.farm.devicemanager.gateway.uplink.service.sensor.alarm;

import cn.sciento.farm.devicemanager.common.constant.AlarmConstant;
import cn.sciento.farm.devicemanager.common.util.DateUtil;
import cn.sciento.farm.devicemanager.common.util.sms.AliyunSmsUtil;
import cn.sciento.farm.devicemanager.dao.entity.*;
import cn.sciento.farm.devicemanager.service.*;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = AlarmConstant.SERVICE_PREFIX + AlarmConstant.SMS)
public class SmsAlarmSendService implements AlarmSendService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AliyunSmsUtil aliyunSmsUtil;

    @Autowired
    private AlarmPersonService alarmPersonService;

    @Autowired
    private AlarmPersonRelService alarmPersonRelService;

    @Autowired
    private AlarmLogService alarmLogService;

    @Autowired
    private TenantSmsResidualService smsResidualService;

    @Autowired
    private AlarmLogSendResultService alarmLogSendResultService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private CollectionService collectionService;

    @Override
    public void send(DevAlarmLog devAlarmLog, List<ResAlarmPerson> personList) {
        DevCollection devCollection = collectionService.getById(devAlarmLog.getCollectionId());
        DevDevice devDevice = deviceService.getById(devCollection.getEui());
        List<String> oldPhones = personList.stream().map(ResAlarmPerson::getPhone).collect(Collectors.toList());
        List<String> newPhones = new ArrayList<>();
        for (String phone : oldPhones) {
            ResAlarmPerson resAlarmPerson = alarmPersonService.getByPhone(phone);
            List<DevAlarmPersonRel> devAlarmPersonRels = alarmPersonRelService.getByPersonId(resAlarmPerson.getId());
            for (DevAlarmPersonRel devAlarmPersonRel : devAlarmPersonRels) {
                long todayZeroTime = DateUtil.getTodayZeroHour().getTime();
                long todayLasTime = DateUtil.getTodayLastHour().getTime();
                Integer alarmLogList = alarmLogService.getByAlarmId(devAlarmPersonRel.getAlarmId(), todayZeroTime, todayLasTime);
                if (alarmLogList <= AlarmConstant.PHONE_DAY_SEND) {
                    newPhones.add(phone);
                }
            }
        }
        if(newPhones.size() != 0) {
            TenantSmsResidual tenantSmsResidual = smsResidualService.getSmsResidual();
            if (tenantSmsResidual == null) {
                return;
            }
            Map<String, String> params = new HashMap<>();
            params.put("collectionName", devAlarmLog.getCollectionName());
            params.put("content", devAlarmLog.getContent());
            for (String phone : newPhones) {
                AlarmLogSendResult sendResult = new AlarmLogSendResult();
                sendResult.setPhone(phone);
                sendResult.setTenantId(devAlarmLog.getTenantId());
                sendResult.setAreaId(devAlarmLog.getAreaId());
                sendResult.setLandId(devDevice.getLandId());
                sendResult.setAlarmName(devAlarmLog.getAlarmName());
                sendResult.setCollectionName(devAlarmLog.getCollectionName());
                sendResult.setActualValue(devAlarmLog.getActualValue());
                if (tenantSmsResidual.getSmsResidual() <= 0 ) {
                    sendResult.setBalance(AlarmConstant.SMS_MESSAGE_RESIDUAL);
                    sendResult.setStatus(0);
                    sendResult.setSendTime(devAlarmLog.getCreateTime());
                    alarmLogSendResultService.create(sendResult);
//               aliyunSmsUtil.sendTenantSms(StringUtils.join(newPhones.toArray(), ","));
                    return;
                }
                String responseMsg = aliyunSmsUtil.sendSms(phone, params);
                logger.info("响应消息:[{}]", responseMsg);
                Map map = JSONObject.parseObject(responseMsg, Map.class);
                String message = map.get("Message").toString();
                if (AlarmConstant.SMS_MESSAGE_OK.equals(message)) {
                    int smsResidual = tenantSmsResidual.getSmsResidual() - 1;
                    tenantSmsResidual.setSmsResidual(smsResidual);
                    int count = smsResidualService.updateSmsResidual(tenantSmsResidual);
                    if (count > 0) {
                        // 发送成功修改状态为1
                        sendResult.setStatus(1);
                        sendResult.setBalance(String.valueOf(smsResidual));
                        sendResult.setSendTime(devAlarmLog.getCreateTime());
                        alarmLogSendResultService.create(sendResult);
                    }
                }
            }
        }
    }
}
